package com.toolmanrln.common.util;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.toolmanrln.common.api.PageResult;
import org.dozer.Mapper;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * dozer拷贝工具
 * @author ToolMan.RLN
 * @since 2020-05-15 16:49
 */
public final class DozerUtil {

    private DozerUtil(){
        throw new UnsupportedOperationException("This class should not be instantiated.");
    }

    /**
     * dozer处理集合的方法：List<S> --> List<T>
     */
    public static <T, S> List<T> mapList(final Mapper mapper, List<S> sourceList, Class<T> targetObjectClass) {
        List<T> targetList = new ArrayList<>();
        for (S s : sourceList) {
            targetList.add(mapper.map(s, targetObjectClass));
        }
        return targetList;
    }

    /**
     * dozer处理Page的方法：Page<S> --> Page<T>
     */
    public static <T, S> IPage<T> mapIPage(final Mapper mapper, IPage<S> sourcePage, Class<T> targetObjectClass) {
        List<T> targetIPageList = mapList(mapper, sourcePage.getRecords(), targetObjectClass);
        IPage<T> targetIPage = new Page<>();
        //不需要深度拷贝
        BeanUtils.copyProperties(sourcePage, targetIPage);
        targetIPage.setRecords(targetIPageList);
        return targetIPage;
    }

    /**
     * dozer处理PageResult的方法：PageResult<S> --> PageResult<T>
     */
    public static <T, S> PageResult<T> mapPageResult(final Mapper mapper, PageResult<S> sourcePage, Class<T> targetObjectClass) {
        List<T> targetIPageList = mapList(mapper, sourcePage.getRows(), targetObjectClass);
        PageResult<T> target = new PageResult<>();
        BeanUtils.copyProperties(sourcePage, target);
        target.setRows(targetIPageList);
        return target;
    }
}
